package jinyilw.swing.visuals.window;

import jinyilw.swing.ColorTools;
import jinyilw.swing.ResourceManager;
import jinyilw.swing.ScreenTools;
import jinyilw.swing.graphics.GraphicsTools;
import jinyilw.swing.image.ImageTools;

import javax.swing.JDialog;
import javax.swing.JFrame;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.concurrent.Executors;

public class ScaleSplashWindow extends Window// 启动窗
{
	private static final long serialVersionUID = -1620527224948235771L;
	BufferedImage image;
	public ScaleSplashWindow() throws HeadlessException
	{
		super(null);
		setBackground(ColorTools.transparentColor);
	}

	public ScaleSplashWindow(URL url) throws HeadlessException
	{
		this();
		setLaunchImage(ImageTools.toBufferedImage(ResourceManager.getImage(url)));
	}

	public ScaleSplashWindow(File file) throws HeadlessException
	{
		this();
		setLaunchImage(ImageTools.toBufferedImage(ResourceManager.getImage(file)));
	}

	private void setLaunchImage(BufferedImage img)
	{
		image = img;
		if (image != null)
		{
			int w = image.getWidth() / 2;
			int h = image.getHeight() / 2;
			if (!ScreenTools.isRetina())
			{
				double systemScaleFactor = GraphicsTools.getSystemScaleFactor();
				int ww = (int) (w * systemScaleFactor);
				int hh = (int) (h * systemScaleFactor);
				image = ImageTools.getShapedImage(image, ww, hh);
			}
			setSize(w, h);
		}
	}

	public void customLaunch()
	{
		setLocationRelativeTo(null);
		setVisible(true);
	}

	public void launch()
	{
		if (image == null)
			return;
		setLocationRelativeTo(null);
		setVisible(true);
		Executors.newSingleThreadExecutor().execute(() -> {
			try
			{
				Thread.sleep(500);
				while (ScaleSplashWindow.this.isVisible())
				{
					EventQueue.invokeLater(() -> {
						try
						{
							for (Window window : (Window[]) Window.class
									.getMethod("getWindows")
									.invoke(null))
								if ((window instanceof JFrame
										|| window instanceof JDialog)
										&& window.isShowing())
								{
									ScaleSplashWindow.this.dispose();
									break;
								}
						} catch (Exception ex)
						{
							for (Frame frame : Frame.getFrames())
								if (frame.isShowing())
								{
									ScaleSplashWindow.this.dispose();
									break;
								}
						}
					});
					Thread.sleep(200);
				}
			} catch (InterruptedException ex)
			{
				EventQueue.invokeLater(ScaleSplashWindow.this::dispose);
			}
		});
	}

	@Override
	public void paint(Graphics g)
	{
		if (image != null)
			g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
	}
}
